<template>
  <el-dialog
    title="重置主账号"
    :visible.sync="visible"
    :append-to-body="true"
    :close-on-click-modal="false"
    :before-close="handleClose"
    width="750px">
    <div v-loading="loading" class="dialog-body">
      <el-steps
        :active="active"
        simple>
        <el-step
          v-for="(item, index) in stepList"
          :key="index"
          :title="item.title"
          :icon="item.icon"
          :status="item.status" />
      </el-steps>
      <div
        v-show="active === 1"
        class="reset-body">
        <div class="reset-body-title">为了保护你的账号安全，请先验证当前账号，验证成功后进行下一步操作</div>
        <el-form
          ref="oldForm"
          :model="oldForm"
          :rules="oldRules"
          label-position="top">
          <el-form-item label="当前手机号" prop="oldPhone">
            <el-input
              v-model="oldForm.oldPhone"
              :disabled="true" />
          </el-form-item>
          <el-form-item label="验证码" prop="oldSmsCode">
            <el-input v-model="oldForm.oldSmsCode">
              <verify-button
                slot="suffix"
                ref="oldVerifyButton"
                @success="oldVerifySuccess"
              />
            </el-input>
          </el-form-item>
        </el-form>
        <div class="dialog-footer" style="margin-top: 50px;">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="resetFirst">下一步</el-button>
        </div>
      </div>
      <div v-show="active === 2" class="reset-body">
        <el-form
          ref="newForm"
          :model="newForm"
          :rules="newRules"
          label-position="top">
          <el-form-item label="新手机号" prop="newPhone">
            <el-input
              v-model="newForm.newPhone" />
          </el-form-item>
          <el-form-item label="验证码" prop="newSmsCode">
            <el-input v-model="newForm.newSmsCode">
              <verify-button
                slot="suffix"
                ref="verifyButton"
                :disabled="!ruleResult.newPhone"
                @success="verifySuccess"
              />
            </el-input>
          </el-form-item>
          <el-form-item label="设置新密码" prop="newPassword">
            <el-input v-model="newForm.newPassword" :type="passwordType">
              <i
                slot="suffix"
                :class="[passwordType === '' ? 'canSee' : 'cannotSeee' ]"
                class="wk wk-icon-eye-solid"
                @click="passwordType = passwordType === '' ? 'password':''" />
            </el-input>
          </el-form-item>
          <el-form-item label="重复新密码" prop="newPasswordCheck">
            <el-input v-model="newForm.newPasswordCheck" :type="passwordCheckType">
              <i
                slot="suffix"
                class="wk wk-icon-eye-solid"
                :class="[passwordCheckType === '' ? 'canSee' : 'cannotSeee' ]"
                @click="passwordCheckType = passwordCheckType === '' ? 'password':''" />
            </el-input>
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <el-button @click="active = 1">上一步</el-button>
          <el-button type="primary" @click="resetSecend">确定</el-button>
        </div>
      </div>
      <div v-show="active === 3">
        <div class="reset-body">
          <i class="wk wk-success reset-body-icon" />
          <div class="reset-body-success">主账号重置完成，点击确定按钮后将自动退出到系统登录页面，</div>
          <div class="reset-body-success">重新登录以验证新账号及密码。</div>
          <div class="dialog-footer" style="margin-top: 100px;">
            <el-button type="primary" @click="reload">确定并退出到登录页</el-button>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { sendSmsAPI, verfySmsAPI, resetManagerUserAPI } from '@/api/login'

import VerifyButton from '@/components/Verify/Button'

import { chinaMobileRegex, checkPasswordRegex } from '@/utils'

export default {
  components: {
    VerifyButton
  },

  props: {
    visible: {
      type: Boolean,
      required: true,
      default: false
    },
    phone: {
      type: String,
      required: true
    },
    resetPasswordRules: {
      type: Array,
      default: () => []
    }
  },
  data() {
    // 检查两次密码是否一致
    var checkPassword = (rule, value, callback) => {
      if (value !== this.newForm.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: true, // 是否显示
      loading: false,
      active: 1, // 进行到第几步
      passwordType: 'password', // 是否显示新密码
      passwordCheckType: 'password', // 是否显示重复密码
      stepList: [
        {
          icon: 'wk wk-icon-user',
          title: '验证当前账号',
          status: 'wait'
        },
        {
          icon: 'wk wk-icon-user-add',
          title: '设置新账号',
          status: 'wait'
        },
        {
          icon: 'wk wk-icon-success2',
          title: '重置完成',
          status: 'wait'
        }
      ],
      oldForm: {
        oldPhone: '',
        oldSmsCode: ''
      },
      newForm: {
        newPassword: '',
        newPasswordCheck: '',
        newPhone: '',
        newSmsCode: ''
      },
      oldRules: {
        oldPhone: [
          { required: true, trigger: 'blur' }
        ],
        oldSmsCode: [
          { required: true, message: '短信验证码不能为空', trigger: 'change' },
          { required: true, message: '短信验证码不能为空', trigger: 'blur' }
        ]
      },
      newRules: {
        newPhone: [
          { required: true, message: '手机号码不能为空', trigger: 'change' },
          { pattern: chinaMobileRegex, message: '目前只支持中国大陆的手机号码', trigger: 'change' }
        ],
        newSmsCode: [
          { required: true, message: '短信验证码不能为空', trigger: 'change' }
        ],
        newPassword: [
          { required: true, message: '密码不能为空', trigger: 'change' },
          { pattern: checkPasswordRegex, message: '密码必须由6-20位字母、数字组成', trigger: 'change' }
        ],
        newPasswordCheck: [
          { required: true, message: '密码不能为空', trigger: 'change' },
          { validator: checkPassword, trigger: 'blur' }
        ]
      },
      // 是true的时候验证通过
      ruleResult: {
        newPhone: null,
        newPassword: null,
        newSmsCode: null,
        newPasswordChec: null
      }
    }
  },
  watch: {
    newForm: {
      handler() {
        this.$nextTick(() => {
          this.changeFormState()
        })
      },
      deep: true
    },

    resetPasswordRules: {
      handler() {
        if (this.resetPasswordRules.length) {
          this.$set(this.newRules, 'newPassword', this.resetPasswordRules)
        }
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    if (this.phone) {
      this.oldForm.oldPhone = this.phone
    }
  },
  beforeDestroy() {},
  methods: {
    /**
     * @description: 关闭当前dialog
     * @param {*}
     * @return {*}
     */
    handleClose() {
      this.$confirm('确认关闭？')
        .then(() => {
          this.$emit('update:visible', false)
        })
    },

    /**
     * @description: 获取旧的验证码
     * @param {*}
     * @return {*}
     */
    oldVerifySuccess(params) {
      sendSmsAPI({
        telephone: this.oldForm.oldPhone,
        type: 2,
        ...(params || {})
      }).then(() => {
        // 开启倒计时
        this.$refs.oldVerifyButton.startTimer()
        this.stepList[0].status = 'process '
      })
    },

    /**
     * @description: 获取新的验证码
     * @param {*}
     * @return {*}
     */
    verifySuccess(params) {
      sendSmsAPI({
        telephone: this.newForm.newPhone,
        type: 1,
        ...(params || {})
      }).then(() => {
        // 开启倒计时
        this.$refs.verifyButton.startTimer()
        this.stepList[1].status = 'process '
      })
    },

    /**
     * @description: 判断是否输入合格，调整状态
     * @param {*}
     * @return {*}
     */
    changeFormState() {
      const form = this.$refs.newForm
      form.$children.forEach(item => {
        if (item.prop) {
          this.ruleResult[item.prop] = item.validateState === 'success'
        }
      })
    },

    /**
     * @description: 验证当前账号时点击下一步
     * @param {*}
     * @return {*}
     */
    resetFirst() {
      this.loading = true
      this.$refs['oldForm'].validate((valid) => {
        if (valid) {
          verfySmsAPI({
            phone: this.oldForm.oldPhone,
            smsCode: this.oldForm.oldSmsCode
          }).then(res => {
            if (res.data === 1) {
              this.active = 2
              this.stepList[0].status = 'finish'
              // 重置倒计时
              this.$refs.oldVerifyButton.resetTimer()
            } else {
              this.$message.error('验证码错误')
            }
            this.loading = false
            this.active = 2
          })
        } else {
          this.loading = false
        }
      })
    },

    /**
     * @description: 设置新账号时点击下一步
     * @param {*}
     * @return {*}
     */
    resetSecend() {
      this.loading = true
      this.$refs['newForm'].validate((valid) => {
        if (valid) {
          resetManagerUserAPI({
            newPassword: this.newForm.newPassword,
            newPhone: this.newForm.newPhone,
            newVerifyCode: this.newForm.newSmsCode,
            oldPhone: this.oldForm.oldPhone,
            oldVerifyCode: this.oldForm.oldSmsCode
          }).then(res => {
            this.active = 3
            this.stepList[1].status = 'finish'
            this.stepList[2].status = 'finish'

            // 重置倒计时
            this.$refs.verifyButton.resetTimer()
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        } else {
          this.loading = false
        }
      })
    },

    /**
     * @description: 重新登陆
     * @param {*}
     * @return {*}
     */
    reload() {
      location.reload()
    }
  }
}
</script>

<style lang="scss" scoped>
.reset-body {
  display: flex;

  // flex-direction: column;
  // flex-wrap: wrap;
  flex-flow: column wrap;
  align-items: center;
  padding-top: 30px;

  &-success {
    font-size: 14px;
    line-height: 30px;
    color: $--color-n500;
  }

  &-icon {
    margin-top: 15px;
    margin-bottom: 15px;
    font-size: 40px;
    color: $--color-primary;
  }

  .dialog-footer {
    align-self: flex-end;
  }

  .el-form {
    margin-top: #{$--interval-base * 2};
  }

  ::v-deep .el-form-item {
    .el-form-item__content {
      width: 400px;
    }

    .el-form-item__label {
      padding: 0 0 10px;
      font-size: 14px;
      font-weight: 500;
      line-height: 1;
      color: $--color-n500;
    }
  }

  ::v-deep .el-input {
    .el-input__inner {
      height: 40px;
      line-height: 40px;
      border-width: 2px;
    }
  }
}

.canSee {
  color: $--color-n700;
}

.cannotSee {
  color: $--color-n50;
}

.el-steps {
  margin-bottom: 15px;

  ::v-deep .el-step__title {
    font-size: 14px;
  }

  ::v-deep .el-step.is-simple .el-step__arrow::before,
  ::v-deep .el-step.is-simple .el-step__arrow::after {
    width: 2px;
    height: 10px;
  }

  ::v-deep .el-step.is-simple .el-step__arrow::after {
    transform: rotate(45deg) translateY(3px);
  }

  ::v-deep .el-step.is-simple .el-step__arrow::before {
    transform: rotate(-45deg) translateY(-2px);
  }
}
</style>
